package controller

import (
	"gobase/app/service"
	"gobase/util"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

//登录控制器
type LoginController struct {
	BaseController
}

//路由注册
func (ctl *LoginController) Router(router *gin.Engine) {
	r := router.Group("login")
	r.GET("/index", ctl.index)
	r.POST("/login", ctl.login)
	r.POST("/logout", ctl.logout)
}

//登录页面
func (ctl *LoginController) index(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", gin.H{
		"title": "Login Page",
	})
}

//登录提交验证
func (ctl *LoginController) login(c *gin.Context) {
	var message = "登录失败:"
	var status = false

	username := c.DefaultPostForm("username", "")
	password := c.DefaultPostForm("password", "")

	if username == "" {
		message += "用户名为空!"
		ctl.ResponseJSON(c, status, message)
	} else if password == "" {
		message += "密码为空!"
		ctl.ResponseJSON(c, status, message)
	}

	userServ := service.NewUserService(c)
	exists, loginUser := userServ.Login(username, password)

	if !exists {
		message += "用户名不存在或密码错误!"
	} else if !loginUser.State {
		message += "用户被禁用，请联系系统管理员!"
	} else {
		message = "登录成功!"
		status = true

		//存入session
		session := sessions.Default(c)
		session.Set(util.LoginAccountName, loginUser.Username)
		session.Set(util.LoginAccountID, loginUser.Id)
		session.Save()
		util.GetLog(c).Info("用户[" + username + "]登录成功!")
	}
	ctl.ResponseJSON(c, status, message)
}

//退出
func (ctl *LoginController) logout(c *gin.Context) {
	//存入session
	user := util.GetCurrLoginUser(c)
	isLogin := (user != "")

	var message = "退出系统成功！"
	if !isLogin {
		message = "您还未登录！"
	} else {
		util.RemoveLoginSession(c)
		util.GetLog(c).Info("用户[" + user + "]退出成功!")
	}
	ctl.ResponseJSON(c, true, message)
}
